package com.click.app.webapp.action;

import com.click.app.model.BalanceEmployee;
import com.click.app.model.CutProcess;
import com.click.app.model.Material;
import com.click.app.model.PeriodPaymentEmployee;
import com.click.app.model.ProcessDressmaker;
import com.click.app.model.ProcessDressmakerPurchaseDetail;
import com.click.app.model.Purchase;
import com.click.app.model.PurchaseDetail;
import com.click.app.model.PurchaseDetailCutProcess;
import com.click.app.model.StorageMaterial;
import com.click.app.service.BalanceEmployeeManager;
import com.click.app.service.CutProcessManager;
import com.click.app.service.MaterialManager;
import com.click.app.service.PeriodPaymentEmployeeManager;
import com.click.app.service.ProcessDressmakerManager;
import com.click.app.service.ProcessDressmakerPurchaseDetailManager;
import com.click.app.service.PurchaseDetailCutProcessManager;
import com.click.app.service.PurchaseDetailManager;
import com.click.app.service.PurchaseManager;
import com.click.app.service.StorageMaterialManager;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 * @author Joel Chuca
 */
public class PurchaseDetailAction extends BaseAction {

    private MaterialManager materialManager;
    private PurchaseDetailManager purchaseDetailManager;
    private StorageMaterialManager storageMaterialManager;
    private PurchaseManager purchaseManager;
    private Purchase purchase;
    private List<Material> materials;
    private List<PurchaseDetail> purchaseDetails;
    private PurchaseDetail purchaseDetail;
    private Material material;
    private Long id;
    private Long idPurchase;
    private List<Purchase> purchaseList;
    private HashMap reportParams;
    private String formatNumberTooltip;
    private List<StorageMaterial> storageMaterialList;
    private CutProcess cutProcess;
    private CutProcessManager cutProcessManager;

    private Double quantity;
    private Double quantityUsed;
    private StorageMaterial storageMaterial;

    private PurchaseDetailCutProcess purchaseDetailCutProcess;
    private PurchaseDetailCutProcessManager purchaseDetailCutProcessManager;

    private ProcessDressmakerPurchaseDetail processDressmakerPurchaseDetail;
    private ProcessDressmakerPurchaseDetailManager processDressmakerPurchaseDetailManager;

    private ProcessDressmaker processDressmaker;
    private ProcessDressmakerManager processDressmakerManager;

    private BalanceEmployeeManager balanceEmployeeManager;

    private PeriodPaymentEmployeeManager periodPaymentEmployeeManager;

    public void setMaterialManager(MaterialManager materialManager) {
        this.materialManager = materialManager;
    }

    public void setPurchaseDetailManager(PurchaseDetailManager purchaseDetailManager) {
        this.purchaseDetailManager = purchaseDetailManager;
    }

    public void setPurchaseManager(PurchaseManager purchaseManager) {
        this.purchaseManager = purchaseManager;
    }

    public void setStorageMaterialManager(StorageMaterialManager storageMaterialManager) {
        this.storageMaterialManager = storageMaterialManager;
    }

    public List getMaterials() {
        return materials;
    }

    public List<PurchaseDetail> getPurchaseDetails() {
        return purchaseDetails;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Material getMaterial() {
        return material;
    }

    public void setMaterial(Material material) {
        this.material = material;
    }

    public PurchaseDetail getPurchaseDetail() {
        return purchaseDetail;
    }

    public void setPurchaseDetail(PurchaseDetail purchaseDetail) {
        this.purchaseDetail = purchaseDetail;
    }

    public Long getIdPurchase() {
        return idPurchase;
    }

    public void setIdPurchase(Long idPurchase) {
        this.idPurchase = idPurchase;
    }

    public Purchase getPurchase() {
        return purchase;
    }

    public String getFormatNumberTooltip() {
        return formatNumberTooltip;
    }


    public String list() {

        if (idPurchase != null) {
            purchase = purchaseManager.get(idPurchase);
            getSession().setAttribute("purchase", purchase);
        } else {
            purchase = ((Purchase) getSession().getAttribute("purchase"));
        }

        if (purchase != null) {
            purchaseDetails = purchaseManager.get(purchase.getId()).getPurchaseDetails();
        } else {
            System.out.println("purchase is null");
            return ERROR;
        }
        return SUCCESS;
    }

    public String edit() {
        System.out.println(" PurchaseDetailAction -> edit() ");

        String ps = ((Purchase) getSession().getAttribute("purchase")).getSupplier().getFullName();
        String pd = ((Purchase) getSession().getAttribute("purchase")).getDate().toString();
        String ptp = ((Purchase) getSession().getAttribute("purchase")).getTotalPrice().toString();
        getSession().setAttribute("ps", ps);
        getSession().setAttribute("pd", pd);
        getSession().setAttribute("ptp", ptp);

        materials = materialManager.getAll();
        if (id != null) {
            purchaseDetail = purchaseDetailManager.get(id);
            material = purchaseDetail.getMaterial();

        } else {
            purchaseDetail = ((PurchaseDetail) getSession().getAttribute("purchaseDetail"));
            // verify if was sended to reload
            if (purchaseDetail != null) {
                material = ((Material) getSession().getAttribute("material"));
            } else {
                purchaseDetail = new PurchaseDetail();
            }
        }
        formatNumberTooltip = getText("formatNumber.tooltip");
        System.out.println(" PurchaseDetailAction -> end edit() ");

        return SUCCESS;
    }

    public String save() {
        System.out.println("PurchaseDetailAction -> save()");
        // get dates of material entity selected
        if (getRequest().getParameter("purchaseDetail.quantity") != null &&
                getRequest().getParameter("purchaseDetail.quantity").length()>0) {
            purchaseDetail.setQuantity(Double.parseDouble(getRequest().getParameter("purchaseDetail.quantity")));

        }
         if (getRequest().getParameter("purchaseDetail.unitPrice") != null &&
                getRequest().getParameter("purchaseDetail.unitPrice").length()>0) {
            purchaseDetail.setUnitPrice(Double.parseDouble(getRequest().getParameter("purchaseDetail.unitPrice")));
        }
        getSession().setAttribute("purchaseDetail", purchaseDetail);
        material = materialManager.get(material.getId());
        getSession().setAttribute("material", material);
        System.out.println("PurchaseDetailAction -> end save()");
        return "reload";
    }
    public String savePurchDetProcessDresssmakerRe(){
        System.out.println("PurchaseDetailAction -> savePurchDetProcessDresssmakerRe()");
        if( (processDressmakerPurchaseDetail.getQuantityFail() == 0 && processDressmakerPurchaseDetail.getPriceQuantityFail()  == 0)  ||
           (processDressmakerPurchaseDetail.getQuantityFail() > 0 && processDressmakerPurchaseDetail.getPriceQuantityFail() >0 )){
            ProcessDressmakerPurchaseDetail proDressPurcDetailAux = processDressmakerPurchaseDetailManager.get(processDressmakerPurchaseDetail.getId());
            Double diffAmountFail = (processDressmakerPurchaseDetail.getQuantityFail() * processDressmakerPurchaseDetail.getPriceQuantityFail()) -
                                          proDressPurcDetailAux.getTotalAmountQuantityFail();
            Double diffQuantFail = processDressmakerPurchaseDetail.getQuantityFail() - proDressPurcDetailAux.getQuantityFail();

            proDressPurcDetailAux.setQuantityFail(processDressmakerPurchaseDetail.getQuantityFail());
            proDressPurcDetailAux.setPriceQuantityFail(processDressmakerPurchaseDetail.getPriceQuantityFail());
            proDressPurcDetailAux.setTotalAmountQuantityFail(
                    processDressmakerPurchaseDetail.getQuantityFail() * processDressmakerPurchaseDetail.getPriceQuantityFail());
            proDressPurcDetailAux = processDressmakerPurchaseDetailManager.save(proDressPurcDetailAux);

            ProcessDressmaker processDressmakerAux = proDressPurcDetailAux.getProcessDressmaker();
            processDressmakerAux.setTotalAmountFail(processDressmakerAux.getTotalAmountFail() + diffAmountFail);
            processDressmakerAux.setTotalCurrentAmount(processDressmakerAux.getTotalCurrentAmount() - diffAmountFail);
            processDressmakerAux = processDressmakerManager.save(processDressmakerAux);

            BalanceEmployee balanceEmployeeAux = processDressmakerAux.getBalanceEmployee();
            //balanceEmployeeAux.setAmountWon(balanceEmployeeAux.getAmountWon() - diffAmountFail);
            balanceEmployeeAux.setTypeBalance(1);
            balanceEmployeeAux.setAmountPaid(balanceEmployeeAux.getAmountPaid() + diffAmountFail);
            balanceEmployeeAux.setObservation(balanceEmployeeAux.getAmountPaid()+" DESC POR MAL USO DE MATERIAL");
            balanceEmployeeAux.setBalance(balanceEmployeeAux.getBalance() - diffAmountFail);
            balanceEmployeeManager.save(balanceEmployeeAux);
            // ------------------------------------------

            PeriodPaymentEmployee perPayEmpl = balanceEmployeeAux.getPeriodPaymentEmployee();
            perPayEmpl.setDiscount(perPayEmpl.getDiscount() + diffAmountFail);
            perPayEmpl.setCurrentAmount(perPayEmpl.getCurrentAmount() - diffAmountFail);
            periodPaymentEmployeeManager.save(perPayEmpl);

            // -------------------------------------------

            PurchaseDetail purchaseDetailAux= proDressPurcDetailAux.getPurchaseDetail();
            purchaseDetailAux.setQuantityFail(purchaseDetailAux.getQuantityFail() + diffQuantFail);
            purchaseDetailAux.setDiscountXfail(purchaseDetailAux.getDiscountXfail() + diffAmountFail);
            purchaseDetailAux.setCurrentQuantity(purchaseDetailAux.getCurrentQuantity() - diffAmountFail);
            purchaseDetail = purchaseDetailManager.save(purchaseDetailAux);

        }
        System.out.println("PurchaseDetailAction -> end savePurchDetProcessDresssmakerRe()");
        return SUCCESS;
    }
    public String doneMaterialCutterUsed(){

        return SUCCESS;
    }

    public String saveButton() throws Exception {

        System.out.println("PurhcseDetailAction -> saveButton()");

        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        if (material == null && material.getId() < 1) {
            saveMessage("Material field wasn't selected");
            return "reload";
        }

        if (purchaseDetail.getQuantity() == null) {
            saveMessage(getText("purchaseDetailRequired.quantity"));
            return "reload";
        }

        if (purchaseDetail.getUnitPrice() == null) {
            saveMessage(getText("purchaseDetailRequired.unitPrice"));
            return "reload";
        }

        Enumeration<String> en = getRequest().getParameterNames();
        while (en.hasMoreElements()) {
            en.nextElement();
        }

        boolean isNew = false;
        isNew = (purchaseDetail.getId() == null);

        if (!isNew) {
            // update storageMaterial if material or purchaseDetail quantity had been changeds
            PurchaseDetail purchaseDetailOld = purchaseDetailManager.get(purchaseDetail.getId());
            StorageMaterial storageOld = materialManager.get(purchaseDetailOld.getMaterial().getId()).getStorageMaterial();
            Double quantityOld = purchaseDetailOld.getQuantity();
            storageOld.decrementStok(quantityOld);
            storageOld = storageMaterialManager.save(storageOld);

        }

        material = materialManager.get(material.getId());
        purchaseDetail.setMaterial(material);
        purchase = (Purchase) getSession().getAttribute("purchase");
        purchaseDetail.setPurchase(purchase);
        purchaseDetail.setQuantity(Double.parseDouble(getRequest().getParameter("purchaseDetail.quantity")));
        purchaseDetail.setUnitPrice(Double.parseDouble(getRequest().getParameter("purchaseDetail.unitPrice")));
        purchaseDetail.setDiscountXfail(0.0D);
        purchaseDetail.setCurrentQuantity(purchaseDetail.getQuantity());
        purchaseDetail.setQuantityFail(0.0D);
        purchaseDetail.setDeleted(true);
        purchaseDetail.setTotalPrice(purchaseDetail.getQuantity() * purchaseDetail.getUnitPrice());
        // update purchase
        purchase.setTotalPrice(purchase.getTotalPrice()+purchaseDetail.getTotalPrice());
        purchase.setRestPrice(purchase.getRestPrice()+purchaseDetail.getTotalPrice());
        purchase = purchaseManager.save(purchase);
        purchaseDetail = purchaseDetailManager.save(purchaseDetail);

        // update storageMaterial
        StorageMaterial storageMaterial = material.getStorageMaterial();
        storageMaterial.incrementStok(purchaseDetail.getQuantity());
        storageMaterial = storageMaterialManager.save(storageMaterial);

        //clean
        getSession().setAttribute("purchaseDetail", null);
        getSession().setAttribute("material", null);

        if (isNew) {
            saveMessage(getText("purchaseDetail.added"));
            return SUCCESS;
        } else {
            saveMessage(getText("purchaseDetail.updated"));
            return INPUT;
        }

    }

    public String addMaterialCutterUsed(){
        System.out.println("addMaterialCutterUsed() ");
        List<Material> materials = purchaseDetailManager.findAllNoPackageDetail();
        storageMaterialList = new ArrayList<StorageMaterial>();
        for (Iterator<Material> it = materials.iterator(); it.hasNext();) {
            Material material = it.next();
            storageMaterialList.addAll(storageMaterialManager.findByIdMaterialNoCero(material.getId()));
        }
        cutProcess = cutProcessManager.get((Long)getSession().getAttribute("idCutProcess"));
        System.out.println("end addMaterialCutterUsed() ");
        return SUCCESS;
    }

    public String deleteMaterialUsed(){
        System.out.println("PurchaseDetailAction -> deleteMaterialUsed() ");
        purchaseDetailCutProcess = purchaseDetailCutProcessManager.get(id);
        cutProcess = purchaseDetailCutProcess.getCutProcess();
        purchaseDetail = purchaseDetailCutProcess.getPurchaseDetail();
        purchaseDetail.setCurrentQuantity( purchaseDetail.getCurrentQuantity() + purchaseDetailCutProcess.getQuantity() );

        List<StorageMaterial> storageMaterialList = storageMaterialManager.findByIdMaterial(purchaseDetail.getMaterial().getId());
        if(!storageMaterialList.isEmpty()){
            storageMaterial = storageMaterialList.get(0);
            storageMaterial.setStock(storageMaterial.getStock() + purchaseDetailCutProcess.getQuantity());
            CutProcess cutProcess = purchaseDetailCutProcess.getCutProcess();
            cutProcess.setTotalAmountFail(cutProcess.getTotalAmountFail() + purchaseDetailCutProcess.getTotalAmountQuantityFail());

            BalanceEmployee balanceEmployee = cutProcess.getBalanceEmployee();
            balanceEmployee.setAmountWon(balanceEmployee.getAmountWon() + purchaseDetailCutProcess.getTotalAmountQuantityFail());

            balanceEmployeeManager.save(balanceEmployee);
            cutProcessManager.save(cutProcess);
            storageMaterialManager.save(storageMaterial);
            purchaseDetailManager.save(purchaseDetail);
            purchaseDetailCutProcessManager.remove(id);
        }
        System.out.println("PurchaseDetailAction -> end deleteMaterialUsed() ");
        return SUCCESS;
    }

    public String getDatasMaterialCutter(){
        System.out.println("getDatasMaterialCutter() ");
        if(id != null){
            storageMaterial = storageMaterialManager.get(id);
        }
        System.out.println("end getDatasMaterialCutter() ");
        return SUCCESS;
    }

    public String editMaterialUsedCutProcess(){
        purchaseDetailCutProcess = purchaseDetailCutProcessManager.get(id);
        return SUCCESS;
    }
    public String getDatasMaterialDressmaker(){
        System.out.println("getDatasMaterialDressmaker() ");
        if(id != null){
            storageMaterial = storageMaterialManager.get(id);
        }
        System.out.println("end getDatasMaterialDressmaker() ");
        return SUCCESS;
    }
    public String savePurchaseDetailCutProcessRe(){
        System.out.println("PurchaseDetailAction -> savePurchaseDetailCutProcessRe() ");
        if((purchaseDetailCutProcess.getQuantityFail() == 0 && purchaseDetailCutProcess.getPriceQuantityFail() == 0)||
           purchaseDetailCutProcess.getQuantityFail() > 0 && purchaseDetailCutProcess.getPriceQuantityFail() != 0){

           PurchaseDetailCutProcess purchDetCutProcAux = purchaseDetailCutProcessManager.get(purchaseDetailCutProcess.getId());
           Double diffQuantFail = purchaseDetailCutProcess.getQuantityFail() - purchDetCutProcAux.getQuantityFail() ;
           purchDetCutProcAux.setQuantityFail(purchaseDetailCutProcess.getQuantityFail());
           purchDetCutProcAux.setPriceQuantityFail(purchaseDetailCutProcess.getPriceQuantityFail());
           purchDetCutProcAux.setTotalAmountQuantityFail(purchaseDetailCutProcess.getQuantityFail() * purchaseDetailCutProcess.getPriceQuantityFail());
           purchDetCutProcAux = purchaseDetailCutProcessManager.save(purchDetCutProcAux);

           CutProcess cutProcess = purchDetCutProcAux.getCutProcess();
           cutProcess.setTotalAmountFail( cutProcess.getTotalAmountFail() +
                                         (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()) );

           cutProcess.setTotalRealAmount(cutProcess.getTotalRealAmount() - (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));
           cutProcess.setTotalCurrentAmount(cutProcess.getTotalCurrentAmount() - (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));

           cutProcess = cutProcessManager.save(cutProcess);

           BalanceEmployee balanceEmployee = cutProcess.getBalanceEmployee();
           //balanceEmployee.setAmountWon(balanceEmployee.getAmountWon() - (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()) );

           balanceEmployee.setTypeBalance(1);
           balanceEmployee.setAmountPaid(balanceEmployee.getAmountPaid() + (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));
           balanceEmployee.setObservation(balanceEmployee.getAmountPaid()+" DESC POR MAL USO DE MATERIAL");
           balanceEmployee.setBalance(balanceEmployee.getBalance() - (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));

           PeriodPaymentEmployee perPayEmpl = balanceEmployee.getPeriodPaymentEmployee();
           perPayEmpl.setDiscount(perPayEmpl.getDiscount() + (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));
           perPayEmpl.setCurrentAmount(perPayEmpl.getCurrentAmount() - (diffQuantFail * purchaseDetailCutProcess.getPriceQuantityFail()));
           periodPaymentEmployeeManager.save(perPayEmpl);

           balanceEmployeeManager.save(balanceEmployee);


           saveMessage(getText("purchaseDetailAction.savePurchaseDetailCutProcessRe.success"));
           System.out.println("PurchaseDetailAction -> end savePurchaseDetailCutProcessRe() ");
           return SUCCESS;
        }else{
           errorMessage(getText("purchaseDetailAction.savePurchaseDetailCutProcessRe.error"));
           System.out.println("PurchaseDetailAction -> error end savePurchaseDetailCutProcessRe() ");
           return ERROR;
        }
    }
    public String deleteMaterialUsedProcessDressmaker(){
       System.out.println("PurchaseDetailAction -> deleteMatProcDressmakUsed() ");
       if(id != null){
            processDressmakerPurchaseDetail = processDressmakerPurchaseDetailManager.get(id);
            PurchaseDetail purchaseDetail = processDressmakerPurchaseDetail.getPurchaseDetail();
            purchaseDetail.setCurrentQuantity(purchaseDetail.getCurrentQuantity() + processDressmakerPurchaseDetail.getQuantity());
            purchaseDetailManager.save(purchaseDetail);
            StorageMaterial storageMaterial =purchaseDetail.getMaterial().getStorageMaterial();
            storageMaterial.setStock(storageMaterial.getStock() + processDressmakerPurchaseDetail.getQuantity());
            storageMaterialManager.save(storageMaterial);
            processDressmakerPurchaseDetailManager.remove(id);
       }
       System.out.println("PurchaseDetailAction -> end deleteMatProcDressmakUsed()");
       return SUCCESS;
   }
    public String cancelProcessDressmakerPurchaseDetail(){
        System.out.println("cancelProcessDressmakerPurchaseDetail() ");

        System.out.println("end cancelProcessDressmakerPurchaseDetail() ");
        return INPUT;
    }
    public String savePurchaseDetailCutProcess(){
        System.out.println(" savePurchaseDetailCutProcess() ");
        if( purchaseDetailCutProcess.getQuantity() <= storageMaterial.getStock()){

            StorageMaterial storageMaterialAux = storageMaterialManager.get(storageMaterial.getId());
            CutProcess cutProcessAux = cutProcessManager.get((Long)getSession().getAttribute("idCutProcess"));
            List<PurchaseDetail> purchaseDetailList = purchaseDetailManager.findByMaterialStockNoCero(storageMaterialAux.getMaterial().getId());
            Double quantity = purchaseDetailCutProcess.getQuantity();

            for (Iterator<PurchaseDetail> it = purchaseDetailList.iterator(); it.hasNext();) {
                PurchaseDetail purchaseDetailIt = it.next();
                PurchaseDetailCutProcess purDetCutProcessAux = new PurchaseDetailCutProcess();
                purDetCutProcessAux.setCutProcess(cutProcessAux);
                purDetCutProcessAux.setPurchaseDetail(purchaseDetailIt);
                purDetCutProcessAux.setQuantityFail(0.0D);
                purDetCutProcessAux.setPriceQuantityFail(0.0D);
                if(quantity >= purchaseDetailIt.getCurrentQuantity()){
                   purDetCutProcessAux.setQuantity(purchaseDetailIt.getCurrentQuantity());
                   quantity = quantity - purchaseDetailIt.getCurrentQuantity();
                   purchaseDetailIt.setCurrentQuantity(0.0D);
                   purchaseDetailManager.save(purchaseDetailIt);
                   purchaseDetailCutProcessManager.save(purDetCutProcessAux);
                }else{

                   purDetCutProcessAux.setQuantity(quantity);
                   purchaseDetailIt.setCurrentQuantity(purchaseDetailIt.getCurrentQuantity() - quantity);
                   quantity = 0.0D;
                   purchaseDetailManager.save(purchaseDetailIt);
                   purchaseDetailCutProcessManager.save(purDetCutProcessAux);
                   break;
                }
            }
            storageMaterialAux.setStock(storageMaterialAux.getStock() - purchaseDetailCutProcess.getQuantity());
            storageMaterialManager.save(storageMaterialAux);
            saveMessage(getText("purchaseDetailAction.savedPurchaseDetailCutProcess"));
            return INPUT;
        }else{
            System.out.println(" savePurchaseDetailCutProcess() - else ");
            storageMaterial = storageMaterialManager.get(storageMaterial.getId());
            errorMessage(getText("purchaseDetailAction.errorPurchaseDetailCutProcess"));
            return ERROR;
        }
    }
    public String saveProcessDressmakerPurchaseDetail(){
        System.out.println("PurchaseDetailAction -> saveProcessDressmakerPurchaseDetail() ");
        if( processDressmakerPurchaseDetail.getQuantity() <= storageMaterial.getStock()){

            StorageMaterial storageMaterialAux = storageMaterialManager.get(storageMaterial.getId());
            ProcessDressmaker processDressmakerAux = processDressmakerManager.get((Long)getSession().getAttribute("pDMid"));
            List<PurchaseDetail> purchaseDetailList = purchaseDetailManager.findByMaterialStockNoCero(storageMaterialAux.getMaterial().getId());

            Double quantity = processDressmakerPurchaseDetail.getQuantity();
            for (Iterator<PurchaseDetail> it = purchaseDetailList.iterator(); it.hasNext();) {
                PurchaseDetail purchaseDetailIt = it.next();
                ProcessDressmakerPurchaseDetail pDressmakerPDetailAux = new ProcessDressmakerPurchaseDetail();
                pDressmakerPDetailAux.setProcessDressmaker(processDressmakerAux);
                pDressmakerPDetailAux.setPurchaseDetail(purchaseDetailIt);
                pDressmakerPDetailAux.setQuantityFail(0.0D);
                pDressmakerPDetailAux.setTotalAmountQuantityFail(0.0D);
                pDressmakerPDetailAux.setPriceQuantityFail(0.0D);
                if(quantity >= purchaseDetailIt.getCurrentQuantity()){
                   pDressmakerPDetailAux.setQuantity(purchaseDetailIt.getCurrentQuantity());
                   quantity = quantity - purchaseDetailIt.getCurrentQuantity();
                   purchaseDetailIt.setCurrentQuantity(0.0D);
                   purchaseDetailManager.save(purchaseDetailIt);
                   processDressmakerPurchaseDetailManager.save(pDressmakerPDetailAux);
                }else{
                   pDressmakerPDetailAux.setQuantity(quantity);
                   purchaseDetailIt.setCurrentQuantity(purchaseDetailIt.getCurrentQuantity() - quantity);
                   quantity = 0.0D;
                   purchaseDetailManager.save(purchaseDetailIt);
                   processDressmakerPurchaseDetailManager.save(pDressmakerPDetailAux);
                   break;
                }
            }
            storageMaterialAux.setStock(storageMaterialAux.getStock() - processDressmakerPurchaseDetail.getQuantity());
            storageMaterialManager.save(storageMaterialAux);
            saveMessage(getText("PurchaseDetailAction -> purchaseDetailAction.savedPurchaseDetailCutProcess"));
            return INPUT;
        }else{
            System.out.println("PurchaseDetailAction -> end saveProcessDressmakerPurchaseDetail() ");
            storageMaterial = storageMaterialManager.get(storageMaterial.getId());
            errorMessage(getText("purchaseDetailAction.errorPurchaseDetailCutProcess"));
            return ERROR;
        }
    }


    public String delete() {

        purchaseDetail.setQuantity(Double.parseDouble(getRequest().getParameter("purchaseDetail.quantity")));
        purchaseDetailManager.remove(purchaseDetail.getId());

        // update purchase
        purchase = (Purchase) getSession().getAttribute("purchase");
        updatePurchase();

        // update storage material
        material = materialManager.get(material.getId());
        StorageMaterial storageMaterial = material.getStorageMaterial();
        storageMaterial.decrementStok(purchaseDetail.getQuantity());
        storageMaterial = storageMaterialManager.save(storageMaterial);

        saveMessage(getText("purchaseDetail.deleted"));

        return "delete";
    }

    public String finalizePurchase() {
        getSession().setAttribute("purchase", null);
        getSession().setAttribute("purchaseDetail", null);
        getSession().setAttribute("packageDetail", null);
        getSession().setAttribute("material", null);
        return SUCCESS;
    }

    private void updatePurchase() {
        purchaseDetails = purchaseManager.get(purchase.getId()).getPurchaseDetails();
        purchase.setPurchaseDetails(purchaseDetails);
        Double priceTotal = new Double(0);
        for (PurchaseDetail pd : purchaseDetails) {
            priceTotal += pd.getTotalPrice();
        }
        purchase.setTotalPrice(priceTotal);
        purchase.setRestPrice(purchase.getTotalPrice() - purchase.getDiscount());
        purchase = purchaseManager.save(purchase);
    }

    public String help(){
        return SUCCESS;
    }

    public String generateJasperReport() {
        System.out.println("PurchaseDetailAction -> generateJasperReport()");
        purchase = ((Purchase) getSession().getAttribute("purchase"));
        purchaseList = new ArrayList<Purchase>();
        purchaseList.add(purchase);

        String pathSubReport = getRequest().getSession().getServletContext().getRealPath("/reports/purchaseDetailSubReport.jasper");
        try {
            JasperReport subReport = (JasperReport) JRLoader.loadObject(new File(pathSubReport));
            reportParams = new HashMap();
            reportParams.put("subReport", subReport);
            reportParams.put("title", getText("purchaseDetail.title"));
            reportParams.put("supplierName", getText("purchase.supplier.fullName"));
            reportParams.put("purchaseDate", getText("purchase.date"));
            reportParams.put("coinName", getText("purchase.coin.name"));
            reportParams.put("totalPrice", getText("purchase.totalPrice"));
            reportParams.put("discount", getText("purchase.discount"));
            reportParams.put("realPrice", getText("purchase.realPrice"));
            reportParams.put("page", getText("display.page"));
            reportParams.put("sTitle", getText("purchaseDetailList.heading"));
            reportParams.put("sMaterial", getText("material"));
            reportParams.put("sUnitMeasure", getText("purchaseDetail.material.unitMeasure"));
            reportParams.put("sQuantity", getText("purchaseDetail.quantity"));
            reportParams.put("sUnitPrice", getText("purchaseDetail.unitPrice"));
            reportParams.put("sTotalPrice", getText("purchaseDetail.totalPrice"));
        } catch (JRException ex) {
            Logger.getLogger(PurchaseDetailAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("PurchaseDetailAction -> end generateJasperReport()");
        return SUCCESS;
    }

    public List<Purchase> getPurchaseList(){
        return purchaseList;
    }

    public HashMap getReportParams() {
        return reportParams;
    }

    public List<StorageMaterial> getStorageMaterialList() {
        return storageMaterialList;
    }

    public void setStorageMaterialList(List<StorageMaterial> storageMaterialList) {
        this.storageMaterialList = storageMaterialList;
    }

    public String  purchaseDetailReview(){
        quantity = ((StorageMaterial)storageMaterialManager.get(id)).getStock();
        return SUCCESS;
    }

    public Double getQuantity() {
        return quantity;
    }

    public void setQuantity(Double quantity) {
        this.quantity = quantity;
    }

    public Double getQuantityUsed() {
        return quantityUsed;
    }

    public void setQuantityUsed(Double quantityUsed) {

        this.quantityUsed = quantityUsed;
    }

    public CutProcess getCutProcess() {
        return cutProcess;
    }

    public void setCutProcess(CutProcess cutProcess) {
        this.cutProcess = cutProcess;
    }

    public CutProcessManager getCutProcessManager() {
        return cutProcessManager;
    }

    public void setCutProcessManager(CutProcessManager cutProcessManager) {
        this.cutProcessManager = cutProcessManager;
    }

    public StorageMaterial getStorageMaterial() {
        return storageMaterial;
    }

    public void setStorageMaterial(StorageMaterial storageMaterial) {
        this.storageMaterial = storageMaterial;
    }

    public PurchaseDetailCutProcess getPurchaseDetailCutProcess() {
        return purchaseDetailCutProcess;
    }

    public void setPurchaseDetailCutProcess(PurchaseDetailCutProcess purchaseDetailCutProcess) {
        this.purchaseDetailCutProcess = purchaseDetailCutProcess;
    }

    public PurchaseDetailCutProcessManager getPurchaseDetailCutProcessManager() {
        return purchaseDetailCutProcessManager;
    }

    public void setPurchaseDetailCutProcessManager(PurchaseDetailCutProcessManager purchaseDetailCutProcessManager) {
        this.purchaseDetailCutProcessManager = purchaseDetailCutProcessManager;
    }

    public ProcessDressmakerPurchaseDetail getProcessDressmakerPurchaseDetail() {
        return processDressmakerPurchaseDetail;
    }

    public void setProcessDressmakerPurchaseDetail(ProcessDressmakerPurchaseDetail processDressmakerPurchaseDetail) {
        this.processDressmakerPurchaseDetail = processDressmakerPurchaseDetail;
    }

    public ProcessDressmakerPurchaseDetailManager getProcessDressmakerPurchaseDetailManager() {
        return processDressmakerPurchaseDetailManager;
    }

    public void setProcessDressmakerPurchaseDetailManager(ProcessDressmakerPurchaseDetailManager processDressmakerPurchaseDetailManager) {
        this.processDressmakerPurchaseDetailManager = processDressmakerPurchaseDetailManager;
    }

    public ProcessDressmaker getProcessDressmaker() {
        return processDressmaker;
    }

    public void setProcessDressmaker(ProcessDressmaker processDressmaker) {
        this.processDressmaker = processDressmaker;
    }

    public ProcessDressmakerManager getProcessDressmakerManager() {
        return processDressmakerManager;
    }

    public void setProcessDressmakerManager(ProcessDressmakerManager processDressmakerManager) {
        this.processDressmakerManager = processDressmakerManager;
    }

    public BalanceEmployeeManager getBalanceEmployeeManager() {
        return balanceEmployeeManager;
    }

    public void setBalanceEmployeeManager(BalanceEmployeeManager balanceEmployeeManager) {
        this.balanceEmployeeManager = balanceEmployeeManager;
    }

    public PeriodPaymentEmployeeManager getPeriodPaymentEmployeeManager() {
        return periodPaymentEmployeeManager;
    }

    public void setPeriodPaymentEmployeeManager(PeriodPaymentEmployeeManager periodPaymentEmployeeManager) {
        this.periodPaymentEmployeeManager = periodPaymentEmployeeManager;
    }

}
